package com.qqtech.qquan.mall.controller;

import java.io.IOException;
import java.sql.Timestamp;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang.StringUtils;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort.Direction;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import com.qqtech.agent.context.AdminPage;
import com.qqtech.core.common.util.JsonUtil;
import com.qqtech.core.common.util.PinyingUtil;
import com.qqtech.core.common.util.StringUtil;
import com.qqtech.core.common.util.TimeUtil;
import com.qqtech.core.frame.model.PageKit;
import com.qqtech.core.frame.model.PageOrder;
import com.qqtech.core.frame.model.Result;
import com.qqtech.core.frame.service.BaseService;
import com.qqtech.qquan.mall.enums.MallShopAuditStatusDictEnum;
import com.qqtech.qquan.mall.enums.MallShopCategoryStatusDictEnum;
import com.qqtech.qquan.mall.model.MallShopCategory;
import com.qqtech.qquan.mall.model.MallShopCategoryQuery;
import com.qqtech.qquan.mall.model.MallShopCategoryVo;
import com.qqtech.qquan.mall.model.MallShopQuery;
import com.qqtech.qquan.mall.service.MallShopCategoryService;
import com.qqtech.qquan.mall.service.MallShopService;
import com.qqtech.qquan.sys.controller.BaseAgentController;

@Controller
@RequestMapping(value = "/mall/shop/category")
public class MallShopCategoryController extends BaseAgentController {
	@Resource
	private MallShopCategoryService mallShopCategoryService;
	@Resource
	private MallShopService mallShopService;

	@Override
	protected BaseService<MallShopCategory> getBaseService() {
		return mallShopCategoryService;
	}

	@RequestMapping(value = "/list", method = RequestMethod.GET)
	public String list() {
		return "/mall/shop/category-list";
	}

	/**
	 * 列表数据
	 * 
	 * @param query
	 * @param request
	 * @param response
	 * @return
	 */
	@RequestMapping(value = "/list", method = RequestMethod.POST)
	@ResponseBody
	public AdminPage list(MallShopCategoryQuery query, HttpServletRequest request, HttpServletResponse response) {
		AdminPage adminPage = new AdminPage();
		if (query == null) {
			query = new MallShopCategoryQuery();
		}
		if (query.getLevel() == null) {
			query.setLevel(1);
		}
		String rows = (String) request.getParameter("rows"); // 每页条数
		query.setSize(Integer.valueOf(rows));
		Pageable pageKit = new PageKit(query.getPage(), query.getSize(), new PageOrder(Direction.DESC, "id"));
		Page<MallShopCategoryVo> page = mallShopCategoryService.queryPageListAdmin(query, pageKit);
		adminPage.setRows(page.getContent());
		adminPage.setTotal(Integer.valueOf(page.getTotalElements() + ""));
		return adminPage;
	}

	/**
	 * 树形
	 * 
	 * @param request
	 * @param response
	 * @return
	 */
	@RequestMapping(value = "/tree", method = RequestMethod.POST)
	@ResponseBody
	public Result tree(HttpServletRequest request, HttpServletResponse response) {
		String parentId = request.getParameter("id");
		if (parentId == null) {
			parentId = "0";
		}
		List<MallShopCategoryVo> list = mallShopCategoryService.queryListByParentId(parentId, null);
		List<Map<Object, Object>> tree = new ArrayList<Map<Object, Object>>();
		if (null != list) {
			for (int i = 0; i < list.size(); i++) {
				MallShopCategoryVo m = (MallShopCategoryVo) list.get(i);
				Map<Object, Object> node = new HashMap<Object, Object>();
				node.put("id", m.getCategoryId());
				node.put("text", m.getName());
				node.put("state", "closed");
				node.put("iconCls", "icon-item");
				Map<String, Object> attributes = new HashMap<String, Object>();
				attributes.put("parentId", m.getParentId());
				node.put("attributes", attributes);
				tree.add(node);
			}
		}
		String json = JsonUtil.toJson(tree);
		try {
			response.getWriter().print(json);
		} catch (IOException e) {
			e.printStackTrace();
		}
		return null;
	}

	@RequestMapping(value = "/add", method = RequestMethod.GET)
	public String add(@RequestParam(required = false) String parentId, HttpServletRequest request,
			HttpServletResponse response) {
		if (StringUtil.isNotBlank(parentId)) {
			MallShopCategoryVo parent = mallShopCategoryService.getByCategoryId(parentId);
			request.setAttribute("parent", parent);
		}
		return "/mall/shop/category-update";
	}

	@RequestMapping(value = "/add", method = RequestMethod.POST)
	@ResponseBody
	public Result doAdd(MallShopCategoryVo mallShopCategoryVo, HttpServletRequest request,
			HttpServletResponse response) {
		Result ret = new Result();
		if (mallShopCategoryVo == null) {
			ret.addErr("参数不能为空");
		} else {
			if (StringUtils.isBlank(mallShopCategoryVo.getName())) {
				ret.addErr("请输入名称");
			} else if (mallShopCategoryVo.getName().length() > 10) {
				ret.addErr("名称长度不能大于10");
			}
			if (mallShopCategoryVo.getStatus() == null) {
				ret.addErr("请输入状态");
			}
			if (mallShopCategoryVo.getType() == null) {
				ret.addErr("请选择种类");
			}
		}
		if (ret.checkForm()) {
			Timestamp now = TimeUtil.now();
			MallShopCategory mallShopCategory = new MallShopCategory();
			mallShopCategory.setName(mallShopCategoryVo.getName().trim());
			mallShopCategory.setFirstLetter(PinyingUtil.getPinYin(mallShopCategory.getName().substring(0, 1), true));
			mallShopCategory.setStatus(mallShopCategoryVo.getStatus());
			mallShopCategory.setNewAt(now);
			mallShopCategory.setOperatorId(super.getLoginUser().getId());
			mallShopCategory.setType(mallShopCategoryVo.getType());
			if (mallShopCategory.getOidx() == null) {
				mallShopCategory
						.setOidx(mallShopCategoryService.getMaxOidxByParentId(mallShopCategoryVo.getParentId()) + 1);
			}
			if (StringUtil.isBlank(mallShopCategoryVo.getParentId())) {
				mallShopCategory.setParentId("0");
				mallShopCategory.setLevel(1);
				// 生成id
				Integer categoryId = Integer.valueOf(mallShopCategory.getLevel() + "00");
				// 最后一条记录
				MallShopCategoryQuery q = new MallShopCategoryQuery();
				q.setParentId(mallShopCategory.getParentId());
				PageOrder page = new PageOrder(Direction.DESC, "id");
				Pageable pageKit = new PageKit(1, 1, new PageOrder(Direction.DESC, "id"));
				List<MallShopCategoryVo> lastList = mallShopCategoryService.queryList(q, pageKit);
				if (lastList != null && !lastList.isEmpty()) {
					MallShopCategoryVo last = lastList.get(0);
					categoryId = Integer.valueOf(last.getCategoryId()) + 1;
				}
				mallShopCategory.setCategoryId(categoryId.toString());
			} else {
				mallShopCategory.setParentId(mallShopCategoryVo.getParentId());
				MallShopCategoryVo parent = mallShopCategoryService.getByCategoryId(mallShopCategoryVo.getParentId());
				mallShopCategory.setLevel(parent.getLevel() + 1);
				// 生成id,父级id+当前id
				Integer categoryId = Integer.valueOf(mallShopCategory.getLevel() + "00");
				// 最后一条记录
				MallShopCategoryQuery q = new MallShopCategoryQuery();
				q.setParentId(mallShopCategory.getParentId());
				Pageable pageKit = new PageKit(1, 1, new PageOrder(Direction.DESC, "id"));
				List<MallShopCategoryVo> lastList = mallShopCategoryService.queryList(q, pageKit);
				if (lastList != null && !lastList.isEmpty()) {
					MallShopCategoryVo last = lastList.get(0);
					categoryId = Integer.valueOf(last.getCategoryId().replace(last.getParentId(), "")) + 1;
				}
				mallShopCategory.setCategoryId(mallShopCategory.getParentId() + categoryId.toString());
				mallShopCategory.setType(parent.getType());
			}
			mallShopCategory.setUpdAt(now);
			mallShopCategoryService.insert(mallShopCategory);
		}
		return ret;
	}

	@RequestMapping(value = "/update/{categoryId}", method = RequestMethod.GET)
	public String update(@PathVariable String categoryId, HttpServletRequest request, HttpServletResponse response) {
		MallShopCategoryVo mallShopCategoryVo = mallShopCategoryService.getByCategoryId(categoryId);
		request.setAttribute("mallShopCategoryVo", mallShopCategoryVo);
		if (null != mallShopCategoryVo && null != mallShopCategoryVo.getParentId()) {
			MallShopCategoryVo parent = mallShopCategoryService.getByCategoryId(mallShopCategoryVo.getParentId());
			request.setAttribute("parent", parent);
		}
		return "/mall/shop/category-update";
	}

	@RequestMapping(value = "/update", method = RequestMethod.POST)
	@ResponseBody
	public Result doUpdate(MallShopCategoryVo mallShopCategoryVo) {
		Result ret = new Result();
		if (mallShopCategoryVo == null || StringUtil.isBlank(mallShopCategoryVo.getCategoryId())) {
			ret.addErr("参数不能为空");
		} else {
			if (StringUtil.isBlank(mallShopCategoryVo.getName())) {
				ret.addErr("请输入分类名称");
			}
			if (mallShopCategoryVo.getStatus() == null) {
				ret.addErr("请输入状态");
			}
			if (mallShopCategoryVo.getOidx() == null) {
				ret.addErr("请输入排序");
			}
			if (mallShopCategoryVo.getType() == null) {
				ret.addErr("请选择种类");
			}
			if (ret.checkForm()) {
				// 判断是否有该类目的店铺
				MallShopCategoryVo old = mallShopCategoryService
						.getByCategoryId(mallShopCategoryVo.getCategoryId());
				if (old != null && old.getStatus().intValue() == MallShopCategoryStatusDictEnum.VALID.getCode()) {
					MallShopQuery shopQuery = new MallShopQuery();
					shopQuery.setCategoryId(mallShopCategoryVo.getCategoryId());
					shopQuery.setAuditStatus(MallShopAuditStatusDictEnum.NORMAL.getCode());
					int c = mallShopService.queryCount(shopQuery);
					if (c > 0) {
						ret.addErr("有" + c + "个店铺在使用该分类，暂不能修改");
					}
				}
			}
		}
		if (ret.checkForm()) {
			MallShopCategory update = new MallShopCategory();
			update.setCategoryId(mallShopCategoryVo.getCategoryId());
			update.setName(mallShopCategoryVo.getName().trim());
			update.setFirstLetter(PinyingUtil.getPinYin(update.getName().substring(0, 1), true));
			update.setStatus(mallShopCategoryVo.getStatus());
			update.setOidx(mallShopCategoryVo.getOidx());
			update.setUpdAt(TimeUtil.now());
			update.setOperatorId(super.getLoginUser().getId());
			update.setType(mallShopCategoryVo.getType());
			mallShopCategoryService.updateByCategoryId(update);
		}
		return ret;
	}

	/**
	 * 获取子分类
	 * 
	 * @param parentId
	 * @return
	 */
	@RequestMapping(value = "/findChildren")
	@ResponseBody
	public Result findChildren(String parentId) {
		Result result = new Result();
		if (parentId != null) {
			List<MallShopCategoryVo> list = mallShopCategoryService.queryListByParentId(parentId, null);
			result.put("childrenList", list);
		}
		return result;
	}
	
	/**
	 * 提供一个选择类目的页面
	 * @param model
	 * @author Ami
	 * @return
	 */
	@RequestMapping(value = "/choose", method = RequestMethod.GET)
	public String choose(Model model) {
		return "/mall/shop/category-choose";
	}
}
